package com.lgy.ms.service.controller.business;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.lgy.ms.api.business.IAppFileService;
import com.lgy.ms.core.bean.LayuiTable;
import com.lgy.ms.core.dto.FileDTO;
import com.lgy.ms.core.exception.BusinessException;
import com.lgy.ms.service.config.GlobalNames;
import com.lgy.ms.service.controller.BaseController;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/file")
public class FileController extends BaseController {

    private Logger log = LoggerFactory.getLogger(getClass());

    @Resource
    private IAppFileService fileService;

    @RequestMapping("/list")
    public String toList(Model model, HttpServletRequest request) {
        model.addAttribute("projectId", request.getParameter("projectId"));
        return "view/file/list";
    }

    @RequestMapping("/getList")
    @ResponseBody
    public LayuiTable getList(Model model) {
        Map<String, Object> reqMap = change2Map();
        PageInfo<FileDTO> pageInfo = fileService.getFileList(reqMap);
        return new LayuiTable(pageInfo);
    }

    @RequestMapping("/add")
    public String toAdd(Model model, HttpServletRequest request) {
        model.addAttribute("projectId", request.getParameter("projectId"));
        return "view/file/add";
    }

    @RequestMapping("/multiUpload")
    @ResponseBody
    public LayuiTable multiUpload(HttpServletRequest req) {
        try {
            List<FileDTO> fileList = processUploadFileAdmin(req, GlobalNames.upload_check);
            log.info("上传成功，文件列表：{}" + JSON.toJSONString(fileList));
            return new LayuiTable(new PageInfo<>(fileList));
        } catch (Exception e) {
            log.error("文件上传失败：" + e.getMessage(), e);
        }
        return null;
    }

    private List<FileDTO> processUploadFileAdmin(HttpServletRequest request, boolean formatCheck) {
        String projectId = request.getParameter("projectId");
        if (!ServletFileUpload.isMultipartContent(request)) {
            throw new BusinessException("文件上传失败,无法获取文件");
        }
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Iterator<String> iterms = multipartRequest.getFileNames();
        List<FileDTO> uploadFileList = Lists.newArrayList();
        FileDTO dto = null;
        while (iterms.hasNext()) {
            String fileType = iterms.next();
            MultipartFile file = multipartRequest.getFile(fileType);
            String fileName = file.getOriginalFilename();
            String extName = FileUtil.extName(fileName);
            if (StrUtil.isEmpty(extName)) {
                throw new BusinessException(fileName + "--此文件无后缀！");
            }
            if (formatCheck) {
                /*******文件格式判断******/
                if (!Arrays.asList(GlobalNames.upload_format_limit.split(",")).contains(extName.toLowerCase())) {
                    throw new BusinessException(fileName + "--文件格式不支持");
                }
                /*******文件大小判断*******/
                if ((file.getSize() > GlobalNames.upload_file_size)) {
                    throw new BusinessException(fileName + "--文件超过大小限制(10M)");
                }
            }
            String accessUrl = null;//图片访问路径
            try {
                accessUrl = storeFileAdmin(file, fileName, projectId);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                throw new BusinessException("图片上传失败");
            }
            dto = new FileDTO();
            dto.setUrl(accessUrl);
            dto.setSize(getSize(file.getSize()));
            dto.setFileName(fileName);
            uploadFileList.add(dto);
        }
        return uploadFileList;
    }

    private String storeFileAdmin(MultipartFile file, String fileName, String projectId) throws Exception {
        StringBuilder path = new StringBuilder();//存储地址
        StringBuilder sbUrl = new StringBuilder(GlobalNames.upload_urlPrefix);//访问路径
        path.append(GlobalNames.upload_file_path);
        String relativePath = "filePath/" + projectId + "/" + DateUtil.today() + "/";
        path.append(relativePath);
        sbUrl.append(relativePath);
        File fPath = new File(path.toString());
        if (!fPath.exists()) {
            fPath.mkdirs();
        }
        path.append(fileName);
        sbUrl.append(fileName);
        file.transferTo(new File(path.toString()));
        return sbUrl.toString();
    }

    private String getSize(Long size) {
        BigDecimal bd = new BigDecimal(size / 1048576f).setScale(1, BigDecimal.ROUND_HALF_UP);
        if (bd.floatValue() >= 0.1) {
            return bd + "MB";
        } else {
            return new BigDecimal(size / 1024f).setScale(1, BigDecimal.ROUND_HALF_UP).intValue() + "KB";
        }
    }
}
